package controllers

import (
	"2301_article/models"
	"math"
)

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type MsgJsonR struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Size    int         `json:"size"`
	Sumpage int         `json:"sumpage"`
	Count   int64       `json:"count"`
}

func (c *MainController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	title := c.GetString("title")
	content := c.GetString("content")
	author := c.GetString("author")
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "请选择文件上传",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	path := "/static/img/" + header.Filename
	c.SaveToFile("img", path)
	var article = models.Article{
		Tittle:  title,
		Content: content,
		Author:  author,
		Img:     "http://127.0.0.1:8080" + path,
	}
	err = models.DB.Create(&article).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: article,
		}
		c.ServeJSON()
	}
}
func (c *MainController) Page() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Article{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size
	var allarticle []models.Article
	err := models.DB.Offset(offset).Limit(size).Find(&allarticle).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "分页查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = MsgJsonR{
			Code:    200,
			Msg:     "分页查询成功",
			Data:    allarticle,
			Page:    page,
			Size:    size,
			Sumpage: sumpage,
			Count:   count,
		}
		c.ServeJSON()
	}
}
func (c *MainController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Article{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
